package com.hh.admin.discount.service.impl;

import java.io.File;
import java.io.IOException;
import javax.servlet.http.HttpSession;
import org.apache.commons.io.FileUtils;
import com.hh.admin.discount.service.UpLoadFileService;
import com.hh.common.util.UUIDGenerator;

/**
 * 文件上传实现类
 * @author chenem
 *
 */
public class UpLoadFileServiceImpl implements UpLoadFileService {
	
	/**
	 * 保存多个文件，文件名称随机生成
	 * @param session
	 * @param ufile           文件对象数组
	 * @param ufileFileName   文件名称数组
	 * @param path            文件存放路径，相对路径
	 */
	public void upLoadImages(HttpSession session,File[] ufile,String[] ufileFileName,String path){
		String targetDirectory = session.getServletContext().getRealPath(path);
        try {
			if(ufile != null && ufile.length>0){
				for (int i=0;i<ufile.length;i++){
				    File target = new File(targetDirectory, UUIDGenerator.getUUID()+ufileFileName[i].substring(ufileFileName[i].lastIndexOf(".")).toLowerCase());
				    FileUtils.copyFile(ufile[i], target); 
				}
			}
		} catch (IOException e) {
			try {
				throw new Exception("文件上传错误！") ;
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
	}
	
	/**
	 * 保存文件
	 * @param session
	 * @param ufile          文件对象
	 * @param ufileFileName  文件名称
	 * @param path           文件存放路径，相对路径
	 * @param fileName       文件保存后的名称
	 */
	public void upLoadImage(HttpSession session,File ufile,String ufileFileName,String path,String fileName){
		String targetDirectory = session.getServletContext().getRealPath(path);
        try {
		    File target = new File(targetDirectory, fileName+ufileFileName.substring(ufileFileName.lastIndexOf(".")).toLowerCase());
		    FileUtils.copyFile(ufile, target); 
		} catch (IOException e) {
			try {
				throw new Exception("文件上传错误！") ;
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
	}
	
	public void deleteImage(HttpSession session, String filePath, String fileName) {
		String realPath = session.getServletContext().getRealPath(filePath) ;
		File file = new File(realPath + File.separator + fileName) ;
		if(file.isFile()) {
			file.delete() ;
		}
	}
	
	/**
	 * 根据文件的绝对路径删除文件
	 * @param filePath
	 */
	public void deleteImage(String filePath) {
		File file = new File(filePath) ;
		if(file.isFile()) {
			file.delete() ;
		}
	}

}
